package com.chinamobile.iot;

import com.chinamobile.iot.config.MqttConfiguration;
import com.chinamobile.iot.mqtt.interception.MessageHandler;
import com.chinamobile.iot.mqtt.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

@EnableFeignClients
@SpringBootApplication
public class App implements CommandLineRunner, ApplicationContextAware {

    private ConfigurableApplicationContext context;
    private Logger logger = LoggerFactory.getLogger(App.class);
    @Autowired
    private Server server;
    @Autowired(required = false)
    @Qualifier("extendMessageHandler")
    private MessageHandler messageService;
    @Autowired
    private MqttConfiguration mqttConfiguration;


    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = (ConfigurableApplicationContext) applicationContext;
    }

    @Override
    public void run(String... args) throws Exception {
        if (messageService != null) {
            if (!messageService.init()) {
                logger.info("init message service failed, the program will shutdown");
                context.close();
                return;
            }
        }
        // 启动mqtt server
        server.startServer();
        logger.info("mqtt_broker started");
    }
}
